package com.paul.web.exception;

import com.alibaba.fastjson.JSON;
import com.paul.common.bean.ApiResult;
import com.paul.common.exception.ExceptionCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ：zmk
 * @date ：Created in 2021/11/12 16:36
 * @description：当未登录或者token失效访问接口时，自定义的返回结果
 */
@Component
public class EntryPointUnauthorizedHandler implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        String uriPath = request.getRequestURI();
        String err = response.getHeader("err");
        ApiResult jsonResult = new ApiResult();

        if (StringUtils.isNotBlank(err)) {
            jsonResult = JSON.parseObject(err, ApiResult.class);
            jsonResult.setMsg(jsonResult.getMsg());
            jsonResult.setCode(jsonResult.getCode());
        } else {
            jsonResult.setMsg("无权访问");
            jsonResult.setCode(401);
        }
        jsonResult.setData("");
        String body = JSON.toJSONString(jsonResult);
        ResponseHelper.print(response, body, ExceptionCode.UNAUTHORIZED.value());
    }
}